package com.example.gzysmartcity.viewmodel;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.blankj.utilcode.util.ThreadUtils;
import com.example.gzysmartcity.repository.local.MyUserDB;
import com.example.gzysmartcity.repository.model.MyUser;
import com.example.gzysmartcity.repository.model.UserInfo;
import com.example.gzysmartcity.repository.remote.State;
import com.example.gzysmartcity.utils.NetworkUtil;

public class LoginViewModel extends ViewModel {
    private final MutableLiveData<State> logoinLiveData = new MutableLiveData<>();
    private UserInfo.DataBean userList;

    public void getLogin(String user, String pass) {
        ThreadUtils.executeByCached(new ThreadUtils.Task<UserInfo>() {
            @Override
            public UserInfo doInBackground() throws Throwable {
                String url = "getUserInfoLoginNameAndPwd?loginName=" + user + "&password=" + pass;
                return NetworkUtil.getInstance().get(url, null, UserInfo.class, 0);
            }

            @Override
            public void onSuccess(UserInfo result) {
                userList=result.getData();
                if (!result.getMessage().equals("SUCCESS")) {
                    logoinLiveData.setValue(State.FAIL);
                    return;
                }
                userList = result.getData();
                logoinLiveData.setValue(State.SUCCESS);
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFail(Throwable t) {
                logoinLiveData.setValue(State.FAIL);
            }
        });
    }

    public void insertMyUserDB(){
        UserInfo.DataBean u=userList;
        MyUserDB.insert(new MyUser(u));
    }

    public LiveData<State> getLiveData() {
        return logoinLiveData;
    }

    public UserInfo.DataBean getUserList() {
        return userList;
    }
}
